/**
 * @author GhostWei
 */
var col = document.getElementsByTagName("script");
var jsrc = col.item(col.length-1).src; 
var i = jsrc.indexOf("?"); 
var params = jsrc.substr(i + 1, jsrc.length).replace('&amp;', '&').split('&');

var collect = {
	_form: null,
	_url: null,
	_params: [],
	_sParams: [],
	_button: null,
	_stop: null,
	_ptable: null,
	_ptdiv: null,
	_statistics: {'error': 0, 'message': 0},
	isStopped: false,
	isFirstTime: true,
	doStart: function() {		
		if(!this._form) {
			alert('Can not found the POST FORM OR URL.');
			return false;
		}
		this._url = this._form.attr('action');
		this._button = $('button#startButton');
		this._stop = $('button#stopButton');
		this._ptable = $('table#processTable');
		this.initParams();
		this._button.hide();
		this._stop.show();
		this.isStopped = false;
		this.send();
		return false;
	},
	doStop: function() {
		this._button.show();
		this._stop.hide();
		this.isStopped = true;
	},
	doComplete: function(msg) {
		$('table#processTable tr.w').detach();
		var _msg = typeof(msg) == 'undefined' ? '' : msg;
		var time = this._timer(new Date());
		this._ptable.append('<tr><td class="id">' + time + '</td><td class="id blue">COMPLETE</td><td class="green">' + _msg + '</td></tr>');
		this._button.show();
		this._stop.hide();
	},
	send: function() {
		if(this.isStopped == true){
			this._error('STOPPED', 0);
			return false;
		}
		var data = [];
		for(var key in this._sParams) {
			if(key == 'error') continue;
			data.push(key + '=' + encodeURIComponent(this._sParams[key]));
		}
		if(this.isFirstTime) {
			data.push('first_time=1');
		}
		_data = this._params.join('&') + '&' + data.join('&');
		var self = this;
		$.ajax({type:'POST',dataType:'json',url:this._url,data:_data,success:function(json, status){
			if(self.isStopped == true) {
				self._error('STOPPED', 0);
				return false;
			}
			self.isFirstTime = false;
			try {
				if(json.status == 0) {
					throw json;
				}
				if(typeof(json.complete) == 'undefined' || json.complete == 1) {
					self.doComplete(json.message);
					return false;
				}
				if(typeof(json.params) != 'undefined' && typeof(json.params.error) != 'undefined') {
					self._statistics.error++;
					$('#_processStat_error').html(self._statistics.error);
				}
				self._message(json.message, status);
				self._sParams = json.params;
				self.send();
			} catch (e) {
				self._error(e.message, 0);
				if($('#ignoreError').attr('checked')) {
					self._message('Restarting ....', 200);
					self.restart();
				}
			}
		}, error: function (req, msg, e) {
			self._error(req['statusText'], req['status']);
			if($('#ignoreError').attr('checked')) {
				self._message('Restarting ....', 200);
				self.restart();
			}
		}, timeout: 30000});
		return false;
	},
	restart: function() {
		var self = this;
		setTimeout(function(){self.doStart();}, 1000);
	},
	_error: function(msg, code) {
		this._statistics.error++;
		$('#_processStat_error').html(this._statistics.error);
		$('table#processTable tr.w').detach();
		var time = this._timer(new Date());
		this._ptable.append('<tr><td class="id">' + time + '</td><td class="id red">ERROR</td><td><strong class="red">' + msg + '</strong></td></tr>');
		this._optimize(true);
		this.doStop();
	},
	_message: function(msg, code) {
		this._statistics.message++;
		$('#_processStat_message').html(this._statistics.message);
		$('table#processTable tr.w').detach();
		var title = (code == 0) ? '<strong class="red">COMPLETE</strong>' : 'MESSAGE';
		var time = this._timer(new Date());
		this._ptable.append('<tr><td class="id">' + time + '</td><td class="id green">' + title + '</td><td>' + msg + '</td></tr>');
		this._optimize();
	},
	_timer: function(date) {
		var h = date.getHours().toString(); h = h.length==1 ? '0'+h : h;
		var s = date.getSeconds().toString(); s = s.length==1 ? '0'+s : s;
		var c = date.getMinutes().toString(); c = c.length==1 ? '0'+c : c;
		return h + ':' + c + ':' + s;
	},
	_optimize: function(e) {
		if(this._statistics.message + this._statistics.error > 88) {
			$('table#processTable tr:first-child').detach();
		}
		if(typeof(e) == 'undefined') {
			this._ptable.append('<tr class="w"><td colspan="3"><p class="waiting">WAITING ...............</p></td></tr>');
		}
		this._ptdiv.scrollTop = this._ptdiv.scrollHeight;
	},
	resetParams: function() {
		this._sParams = [];
	},
	initParams: function() {
		this._params = [];
		var serializeData = this._form.serializeArray();
		for(var i in serializeData) {
			this._params.push(serializeData[i]['name'] + '=' + encodeURIComponent(serializeData[i]['value']));
		}
	},
	initialize: function() {
		for(var k = 0; k < params.length; k++) {
			var key = params[k].substring(0, parseInt(params[k].indexOf('=')));
			var val = params[k].substring(parseInt(params[k].indexOf('=') + 1));
			if(key.toLowerCase() == 'item') {
				this._form = $('#' + val);
			}
		}
		this._ptdiv = document.getElementById('_processTable');
		this.resize();
		$(window).resize(function(){collect.resize();});
	},
	resize: function() {
		var n = $('.sbutton').height() + 14;
		var h = $(window).height() - $('.breadcrumb').height() - n - 112;
		$('#left').css({'height': h + 'px'});
		this._ptdiv.style.height = (h + n) + 'px';
	}
};
$(document).ready(function(){collect.initialize();});
